package com.dk.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dk.pojo.goods.TbGoods;
import com.dk.pojo.goods.TbGoodsDesc;
import com.dk.pojo.item.TbItem;
import com.dk.service.goods.GoodsService;
import com.dk.service.item.ItemPageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Component
public class ItemPageSerivceImpl implements ItemPageService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${freemarker.pageDir}")
    private String pageDir;

    @Reference
    private GoodsService goodsService;

    @Override
    public void freemarkerItemPage(Long goodsId) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter = null;
        try {
            // 创建模板
            Template template = configuration.getTemplate("item.ftl");
            // 创建数据模型
            Map map = new HashMap();
            // 获取goods信息
            TbGoods goods = goodsService.getGoodsById(goodsId);
            map.put("goods",goods);
            // 获取desc信息
            TbGoodsDesc goodsDesc = goodsService.getGoodsDescById(goodsId);
            map.put("goodsDesc",goodsDesc);
            // 根据goodsid 获取item
            List<TbItem> itemList = goodsService.listItem(goodsId);
            map.put("itemList",itemList);
            // 创建文件输出流
            fileWriter = new FileWriter(pageDir + goodsId +".html");
            template.process(map,fileWriter);

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
